package fr.flogo.destinee.objects.textures;

import java.nio.IntBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.opengl.GLUtils;

public abstract class TexturesUtils {

	private static TexturesUtils instance = null;

	private static Matrix yFlipMatrix;

	static {
		yFlipMatrix = new Matrix();
		yFlipMatrix.postScale(1, -1);
	}

	private Context context;

	public TexturesUtils(GL10 gl, Context context) {
		if (TexturesUtils.instance == null) {
			TexturesUtils.instance = this;
		}
		this.context = context;
	}

	protected IntBuffer loadNewTexture(GL10 gl, int ressourceId) throws Exception {
		Bitmap texture;
		IntBuffer textureBuffer = IntBuffer.allocate(1);

		texture = LoadImageTexture(this.context, ressourceId);
		
//		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glGenTextures(1, textureBuffer);
		gl.glBindTexture(GL10.GL_TEXTURE_2D,
				textureBuffer.get(0));
		// setup texture parameters
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
				GL10.GL_LINEAR);
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
				GL10.GL_LINEAR);
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
				GL10.GL_CLAMP_TO_EDGE);
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
				GL10.GL_CLAMP_TO_EDGE);
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, texture, 0);
		texture.recycle();
		return textureBuffer;
	}

	public abstract IntBuffer getTexture(int id);

	static public TexturesUtils getInstance() {
		return TexturesUtils.instance;
	}
	
	public static Bitmap LoadImageTexture(Context context, int ressourceId) throws Exception {
		Bitmap bitmap = null;
		try {

			bitmap = BitmapFactory.decodeResource(context.getResources(),
					ressourceId);
			System.out.println("TextureUtils.load|Bitmap=" + bitmap.getWidth()
					+ " x " + bitmap.getHeight());
			return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), yFlipMatrix, false);
		} finally {
			if (bitmap != null) {
				bitmap.recycle();
			}
		}
	}

}
